package net.begincode.SSO.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ClientFilter implements Filter {
	public static final String LOGIN_PAGE_URL = "http://localhost:8080/SSO-web/core/login.jsp";
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;
		String backURL = request.getParameter("backURL");
		HttpSession session = request.getSession();
		String ticket = (String) session.getAttribute("ticket");
		if(ticket==null||"".equals(ticket)){
			response.sendRedirect(LOGIN_PAGE_URL+"?backURL="+backURL);
			return;
		}else{
			response.sendRedirect(backURL+"?ticket="+ticket);
			session.setMaxInactiveInterval(60*30);
			return;
		}
		
	}

	@Override
	public void destroy() {

	}

}
